<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>集成集成WebSocket示例</title>
</head>
<body>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.4.0/sockjs.min.js"></script>

<div>
    <button id="connect" onclick="connect();">连接</button>
    <button id="disconnect" onclick="disconnect();">断开连接</button>
    <button id="serverTimeId" onclick="getServerTime();">获取服务器端时间</button>
    <hr/>
    <span id="showServerTime"></span>
</div>


<script type="text/javascript">
    var stompClient = null;
    $(function () {
        setConnect(false);
    });

    function setConnect(connected) {
        $("#connect").attr({disabled: connected});
        $("#disconnect").attr({disabled: !connected});
    }

    function connect() {

        var socket = new SockJS('/endpointSocket');
        console.log(socket)
        //创建STOMP客户端连接，目标地址为/endpointSocket的STOMP代理
        stompClient = Stomp.over(socket);


        //打印stomp输出信息
        stompClient.debug = function (str) {
            console.log(str + "\n");
        };
        //建立连接
        stompClient.connect({}, function (frame){
            setConnect(true);
            //连接成功后订阅/topic/getResponse目标发送的消息，该地址在Controller中用@SendTo指定
            stompClient.subscribe('/topic/getResponse', function (response) {
                showResponse(JSON.parse(response.body).responseMessage);
            });
        }
    );
    }

    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnect(false);
    }

    function getServerTime() {
        var message = "The server time is : ";
        //发送消息到服务端，/getServerTime地址是由Controller中的@MessageMapping指定
        stompClient.send("/getServerTime", {}, JSON.stringify({'message': message}));
    }

    function showResponse(message) {
        var response = $("#showServerTime");
        response.html(message);
    }
</script>
</body>
</html>